/**
 *
 * mongo:团队相关库
 * mongo_process流程库
 * @Description: 数据库操作封装  每个文件为一个对象所以会有多个同样文件链接不同的库
 * @author longfa liang
 * @date 2021/7/13
 */
var router = {}
const EventEmitter = require('events')
const myEmitter = new EventEmitter()
const mongodb = require('mongodb')

myEmitter.emit('ready', true)

router.start = function (url, table) {
    router.url = url
    router.table = table
    router.pool = require('../tool/pool')(url)

}

/**同步插入一条
 * @param table 表明
 * @param data  插入内容
 * 返回插入信息
 */
router.insertOne = function (table, data) {
    return new Promise(async (resolve, reject) => {
        var client = await  router.pool.acquire()
        client.db(router.table).collection(table).insertOne(data, async function (err, res) {
            if (err) {
                myEmitter.emit('error', JSON.stringify(err))
                resolve(err)
            } else {
                resolve(res)
            }
            await  router.pool.release(client) //使用完毕归还链接
        })

    })
}


/**同步插入多条
 * @param table 表明
 * @param data  插入内容
 */
router.insertMany = function (table, data) {
    return new Promise(async (resolve, reject) => {
        var client = await  router.pool.acquire()
        client.db(router.table).collection(table).insertMany(data, async function (err, res) {
            if (err) {
                myEmitter.emit('error', JSON.stringify(err))
                resolve(err)
            } else {
                resolve(res)
            }
            await  router.pool.release(client) //使用完毕归还链接
        })
    })
}

/**
 *查询
 * @param table 表格
 * @param data  条件
 * @param project 返回筛选
 * @param skip  从多少条开始查
 * @param limit  查询多少条
 * @param sort  排序
 * @param count  统计总条数
 * @returns {Promise<any>}
 */
router.find = function (table, data, project, skip, limit, sort, count) {
    return new Promise(async (resolve, reject) => {
        if (typeof data != 'object') {
            data = {}
        }
        if (typeof table != 'string') {
            throw 'function find table parameter not is string '
        }
        var client = await  router.pool.acquire()
        let list = client.db(router.table).collection(table).find(data)
        if (project) {
            list = list.project(project)
        }
        if (skip || skip === 0) { //从第多少条开始
            if (typeof skip != 'number') {
                throw 'function find skip parameter not is number '
            }
            list = list.skip(skip)
        }
        if (limit || skip === 0) {//查询多少条
            if (typeof limit != 'number') {
                throw 'function find limit parameter not is limit '
            }
            list = list.limit(limit)
        }
        if (sort) { //排序
            if (typeof sort != 'object') {
                throw 'function find sort parameter not is object '
            }
            list = list.sort(sort)
        }
        var row
        if (count) {
            row = await list.count()
        }
        list.toArray((err, rows) => {
            if (err) {
                myEmitter.emit('error', JSON.stringify(err))
                resolve(err)
            } else {
                if (count) {
                    resolve([rows, row])

                } else {

                    resolve(rows)
                }
            }
        })

        await  router.pool.release(client) //使用完毕归还链接
    })

}


/**
 * 查询单条
 * @param table
 * @param data
 * @returns {Promise<any>}
 */
router.findOne = function (table, data) {
    return new Promise(async (resolve, reject) => {
        var client = await  router.pool.acquire()
        client.db(router.table).collection(table).findOne(data, async function (err, res) {
            if (err) {
                myEmitter.emit('error', JSON.stringify(err))
                resolve(err)
            } else {
                resolve(res)
            }

        })
        await  router.pool.release(client) //使用完毕归还链接
    })
}


/**
 * 获取objectId
 * @param objectId
 * @returns {*}
 * @constructor
 */
router.ObjectID = function (objectId) {
    return new mongodb.ObjectID(objectId)
}

/**同步修改单条
 * @param table 表明
 * @param data  条件
 * @param value  修改数据
 * @returns {Promise<any>}
 */
router.updateOne = function (table, data, value) {
    console.log('数据库update', table, JSON.stringify(data), JSON.stringify(value))
    return new Promise(async (resolve, reject) => {

        var client = await  router.pool.acquire()
        client.db(router.table).collection(table).updateOne(data, value, async function (err, res) {
            if (err) {
                console.log(err)
                myEmitter.emit('error', JSON.stringify(err))
                resolve(err)
            } else {
                resolve(res)
            }
            await  router.pool.release(client) //使用完毕归还链接
        })
    })

}
/**同步修改满足条件的
 * @param table 需要修改的表
 * @param data  条件
 * @param value 需要修改的列和值
 * @param upsert 有则修改没有则插入 默认false
 * @param multi 是否全部更新 默认false
 */
router.update = function (table, data, value, upsert, multi) {
    console.log('数据库update', table, JSON.stringify(data), JSON.stringify(value))
    return new Promise(async (resolve, reject) => {
        var client = await  router.pool.acquire()
        client.db(router.table).collection(table).updateMany(data, value, { upsert: upsert || false, multi: multi || false }, async (err, row) => {
            if (err) {
                myEmitter.emit('error', JSON.stringify(err))
                resolve(err)
            } else {
                resolve(row)
            }
            await  router.pool.release(client) //使用完毕归还链接
        })
    })
}

/**同步删除单条 deleteOne (table, data)
 * @param table 需要修改的表
 * @param data  条件
 */
router.deleteOne = function (table, data) {
    return new Promise(async (resolve, reject) => {

        var client = await  router.pool.acquire()
        client.db(router.table).collection(table).deleteOne(data, async (err, res) => {

            if (err) {
                myEmitter.emit('error', JSON.stringify(err))
                resolve(err)
            } else {
                resolve(res)
            }
            await  router.pool.release(client) //使用完毕归还链接
        })
    })
}
/**同步删除满足条件的deleteAll(table, data)
 * @param table 需要修改的表
 * @param data  条件
 */
router.deleteAll = function (table, data) {
    return new Promise(async (resolve, reject) => {
        var client = await  router.pool.acquire()
        client.db(router.table).collection(table).deleteMany(data, async (err, res) => {
            if (err) {
                myEmitter.emit('error', JSON.stringify(err))
                resolve(err)
            } else {
                resolve(res)
            }
            await  router.pool.release(client) //使用完毕归还链接
        })
    })
}
module.exports = router
router.event = myEmitter
